package com.srwl.mytx.widget;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.OfferRecordAdapter;
import com.srwl.mytx.adapter.WrapContentLinearLayoutManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Orders;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.MoneyInputCheck;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.utils.Utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 拍卖出价对话框
 */
public class OfferDialogV1 extends BottomSheetDialog implements CountDownView.InteractionListener {
    private static final String TAG = "OfferDialogV1";
    private InteractionListener listener;
    private OfferRecordAdapter offerRecordAdapter;
    private List<Orders> ordersList = new ArrayList<>();
    private int page = 1;
    private boolean hasNextPage;
    private Topic topic;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_bind_increment)
    TextView tv_bidIncrement;
    @BindView(R.id.tv_current_price)
    TextView tv_currentPrice;
    @BindView(R.id.refresh_layout)
    MaterialSmoothRefreshLayout refreshLayout;
    @BindView(R.id.et_offer_amount)
    EditText et_offerAmount;
    @BindView(R.id.btn_offer)
    Button btn_offer;
    @BindView(R.id.rv_offer_list)
    RecyclerView rv_offerList;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.count_down_view)
    CountDownView countdownView;
    @BindView(R.id.left_layout)
    View leftLayout;

    @BindView(R.id.tv_popup_msg)
    TextView mTvPopupMsg;
    @BindView(R.id.tv_deposit)
    TextView tv_deposit;
    private MoneyInputCheck moneyInputCheck;
    private boolean isAuctionEnd;
    private Context context;
    private View mPopupView;
    //  private PopupWindow mPopupWindow;

    public OfferDialogV1(@NonNull Context context) {
        super(context);
        this.context = context;
    }

    public OfferDialogV1(@NonNull Context context, Topic topic, final InteractionListener listener) {
        super(context);//, R.style.BottomDialog_v1
        this.context = context;
        this.listener = listener;
        this.topic = topic;
        init(context);
    }

    private void init(@NonNull Context context) {
        setContentView(R.layout.layout_offer_dialog);
        ButterKnife.bind(this);
        addScrollListener();
        if (topic == null) {
            return;
        }
        countdownView.init(topic.getStartTime(), topic.getStopTime(), this);
        tv_bidIncrement.setText(Utils.moneyFormat(topic.getBidIncrement()));
        tv_title.setText(topic.getTitle());
        tv_currentPrice.setText(Utils.moneyFormat(topic.getPrice()));
        tv_deposit.setText(Utils.moneyFormat(topic.getDeposit()));
        offerRecordAdapter = new OfferRecordAdapter(context, ordersList);
        rv_offerList.setLayoutManager(new WrapContentLinearLayoutManager(context));
        rv_offerList.setAdapter(offerRecordAdapter);
        initRefreshLayout();
        //让自己不能给自己发布的拍卖出价
        if (topic.getuId().equals(UserProfileManager.getInstance().getLoginUserInfo().getuId())) {
            et_offerAmount.setEnabled(false);
        } else {
            initTextChangedListener();
        }
        loadData(true, false);
        btn_offer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //出价只关乎保证金，所以只需要检查用户可支配的余额是否大于保证金即可
                new PayUtils(topic.getDeposit(), context, new PayUtils.InteractionListener() {
                    @Override
                    public void onPrepareComplete(String payPassword) {
                        offerToTopic(payPassword);
                    }
                });
            }
        });
        leftLayout.setOnClickListener((view) -> dismiss());
    }

    private void offerToTopic(String payPassword) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        double offerAmount = Double.valueOf(et_offerAmount.getText().toString());
        Orders orders = new Orders();
        orders.setAmount(offerAmount);
        orders.settId(topic.getId());
        Map<String, Object> body = new HashMap<>();
        if (payPassword != null) {
            body.put("payPassword", payPassword);
        }
        body.put("orders", orders);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .offerToTopic(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            return;
                        }
                        if (result.isError()) {
                            switch (result.getStatus()) {
                                case Constant.PAY_PASSWORD_ERROR:
                                    showToast(btn_offer, context.getString(R.string.pay_password_error));
                                    break;
                                case Constant.UNKNOWN_ERROR:
                                    showToast(btn_offer, context.getString(R.string.system_busy));
                                    break;
                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(btn_offer, context.getString(R.string.balance_not_enough));
                                    break;
                                case Constant.OFFER_ERROR_AMOUNT_LOWER:
                                    showToast(tv_title, context.getString(R.string.offer_amount_lower));
                                    //这种情况是，用户进入页面后，在用户出价之前，其他人已经出过更高了，所以返回出价过低，需要刷新本地页面
                                    refreshData();
                                    break;
                                case Constant.OFFER_BUSY:
                                    showToast(btn_offer, context.getString(R.string.system_busy));
                                    break;
                            }
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 出价完成");
                        JSONObject jsonObject = (JSONObject) result.getData();
                        et_offerAmount.setText("");
                        //只有第一次出价才会返回 保证金，因为保证金扣除一次
                        if (jsonObject.containsKey("deposit")) {
                            Double deposit = jsonObject.getDouble("deposit");
                            UserProfileManager.getInstance().setDeposit(deposit);
                        }
                        Integer offerCount = jsonObject.getInteger("offerCount");
                        tv_currentPrice.setText(Utils.moneyFormat(offerAmount));
                        moneyInputCheck.setMoreThan(offerAmount + topic.getBidIncrement());//出价成功后重置输入检测的下限
                        User loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
                        orders.setUser(loginUserInfo);
                        orders.setOfferCount(offerCount);
                        orders.setCreated(new Date());
                        orders.setStatus(Constant.ORDER_STATUS_INIT);
                        //如果不是第一次出价，则需要判断 出价记录中是否有自己前一次的出价，如果有，删除掉
                        if (offerCount != 1) {
                            for (int i = 0; i < ordersList.size(); i++) {
                                Orders orders1 = ordersList.get(i);
                                if (orders1.getUser().getuId().equals(loginUserInfo.getuId())) {
                                    orders.setId(orders1.getId());//需要设置id,因为在OfferRecordActivity的onActivityResult（）中需要它
                                    //   setResult(RESULT_OK, new Intent().putExtra("orders", orders));

                                    if (ordersList.size() == 1) {
                                        ordersList.remove(0);
                                        ordersList.add(orders);
                                        offerRecordAdapter.notifyItemChanged(0);
                                    } else {
                                        ordersList.remove(i);
                                        ordersList.add(0, orders);
                                        offerRecordAdapter.notifyItemMoved(i, 0);
                                        offerRecordAdapter.notifyItemChanged(0);
                                    }
                                    break;
                                }

                            }
                        } else if (ordersList.size() == 0) {
                            ordersList.add(orders);
                            offerRecordAdapter.notifyItemInserted(0);
                        } else {
                            ordersList.add(0, orders);
                            offerRecordAdapter.notifyItemInserted(0);
                        }

                        if (listener != null) {
                            listener.onOfferSuccess(offerAmount);
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    private void refreshData() {
        page = 1;
        loadData(false, true);
    }

    private void initRefreshLayout() {
        refreshLayout.setDisableRefresh(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(true);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                refreshData();
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false, false);
                } else {
                    refreshLayout.refreshComplete();
                }
            }
        });
    }

    private void initTextChangedListener() {

        moneyInputCheck = new MoneyInputCheck(getContext(), topic.getPrice() + topic.getBidIncrement(), new MoneyInputCheck.InteractionListener() {
            @Override
            public void showErrorMessage(String message) {
                showPopupWindow(message);
                //      et_offerAmount.setError(message);
                btn_offer.setEnabled(false);

            }

            @Override
            public void waitInput() {
                btn_offer.setEnabled(false);
                hidePopupWindow();
            }

            @Override
            public void inputRight() {
                if (!isAuctionEnd) {
                    btn_offer.setEnabled(true);
                }
                hidePopupWindow();
            }
        });
        et_offerAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                moneyInputCheck.onTextChanged(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
                moneyInputCheck.afterTextChanged(s);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        attributes.verticalMargin = Utils.dpToPx(40, getContext());
        getWindow().setAttributes(attributes);
    }

    public void loadData(boolean isFirst, boolean isRefresh) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (isRefresh) refreshLayout.refreshComplete();
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        Map<String, Object> info = new HashMap<>();
        info.put("topicId", topic.getId());
        info.put("page", page);
        info.put("size", 10);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .queryTopicOffer(info)
                .enqueue(new Callback<CommonResult>() {

                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {

                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            return;
                        }
                        JSONObject pageInfo = (JSONObject) result.getData();
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> refreshLayout.setFooterView(new NodataFooter(context)), 2000);
                        }
                        List<Orders> orders = pageInfo.getJSONArray("list").toJavaList(Orders.class);

                        //第一次加载数据或者是刷新数据，把第一个出价作为最高价，因为后端是按出价降序排列
                        if ((isFirst || isRefresh) && orders != null && orders.size() != 0) {
                            Double currentMaxAmount = orders.get(0).getAmount();
                            tv_currentPrice.setText(Utils.numberFormat(currentMaxAmount));
                            if (moneyInputCheck != null) {
                                moneyInputCheck.setMoreThan(currentMaxAmount + topic.getBidIncrement());//出价成功后重置输入检测的下限
                            }
                        }
                        if (isRefresh) {
                            ordersList.clear();
                        }
                        ordersList.addAll(orders);
                        offerRecordAdapter.notifyDataSetChanged();
                        page++;
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, t.getMessage());

                    }
                });
    }

    private void addScrollListener() {

        View view1 = getDelegate().findViewById(R.id.design_bottom_sheet);
        final BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(view1);
        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    dismiss();
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                //   Log.d(TAG, "onSlide:滑动  " + slideOffset);
                if (slideOffset == 1) {
                    leftLayout.setVisibility(View.VISIBLE);
                } else {
                    leftLayout.setVisibility(View.INVISIBLE);

                }

            }
        });
    }

    @Override
    public void onCountDownStop() {
        isAuctionEnd = true;
        et_offerAmount.setVisibility(View.GONE);
        btn_offer.setVisibility(View.GONE);
    }

    private void showToast(final View view, final String toastContent) {
        Snackbar.make(view, toastContent, Snackbar.LENGTH_LONG).show();
    }

    private void showPopupWindow(String message) {
        mTvPopupMsg.setText(message);
        mTvPopupMsg.setVisibility(View.VISIBLE);

    }

    private void hidePopupWindow() {
        mTvPopupMsg.setVisibility(View.INVISIBLE);

    }

    public interface InteractionListener {

        void onOfferSuccess(double amount);
    }


}
